<template>
  <div class="profile">
    <div v-if="loading" class="loading-container">
      <el-loading />
    </div>
    <div v-else>
      <el-row :gutter="20">
      <!-- 个人信息卡片 -->
      <el-col :span="8">
        <el-card class="profile-card">
          <div class="profile-header">
            <el-avatar :size="100" :src="avatarUrl">
              {{ userInfo.realName?.charAt(0) || userInfo.username?.charAt(0) || 'U' }}
            </el-avatar>
            <h3>{{ userInfo.realName || userInfo.username || '用户' }}</h3>
            <p>{{ userInfo.email || '暂无邮箱' }}</p>
          </div>
          
          <div class="profile-info">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="用户名">{{ userInfo.username || '-' }}</el-descriptions-item>
              <el-descriptions-item label="邮箱">{{ userInfo.email || '-' }}</el-descriptions-item>
              <el-descriptions-item label="姓名">{{ userInfo.realName || '-' }}</el-descriptions-item>
              <el-descriptions-item label="手机号">{{ userInfo.phone || '-' }}</el-descriptions-item>
              <el-descriptions-item label="状态">
                <el-tag :type="getStatusType(userInfo.status || 'ACTIVE')">
                  {{ getStatusText(userInfo.status || 'ACTIVE') }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="最后登录">
                {{ userInfo.lastLoginAt ? formatDate(userInfo.lastLoginAt) : '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="创建时间">
                {{ userInfo.createdAt ? formatDate(userInfo.createdAt) : '-' }}
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <div class="profile-actions">
            <el-button type="primary" @click="handleEditProfile">
              <el-icon><Edit /></el-icon>
              编辑资料
            </el-button>
            <el-button @click="handleChangePassword">
              <el-icon><Lock /></el-icon>
              修改密码
            </el-button>
          </div>
        </el-card>
      </el-col>

      <!-- 角色和权限信息 -->
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>角色和权限</span>
            </div>
          </template>
          
          <el-tabs v-model="activeTab">
            <el-tab-pane label="我的角色" name="roles">
              <div class="roles-section">
                <el-row :gutter="20">
                  <el-col
                    v-for="userRole in userInfo.userRoles || []"
                    :key="userRole.role.id"
                    :span="8"
                  >
                    <el-card class="role-card" shadow="hover">
                      <template #header>
                        <div class="role-header">
                          <span>{{ userRole.role.name }}</span>
                          <el-tag :type="getRoleStatusType(userRole.role.status)">
                            {{ getRoleStatusText(userRole.role.status) }}
                          </el-tag>
                        </div>
                      </template>
                      <p>{{ userRole.role.description || '暂无描述' }}</p>
                    </el-card>
                  </el-col>
                </el-row>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="我的权限" name="permissions">
              <div class="permissions-section">
                <el-tree
                  :data="permissionTree"
                  :props="{ label: 'name', children: 'children' }"
                  node-key="id"
                  default-expand-all
                  :expand-on-click-node="false"
                >
                  <template #default="{ node, data }">
                    <div class="permission-node">
                      <span class="permission-name">{{ data.name }}</span>
                      <span class="permission-module">{{ data.module }}</span>
                    </div>
                  </template>
                </el-tree>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
    </div>

    <!-- 编辑资料对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑个人资料"
      width="500px"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="100px"
      >
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :http-request="handleAvatarUpload"
          >
            <img v-if="editForm.avatar" :src="editForm.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="姓名" prop="realName">
          <el-input v-model="editForm.realName" placeholder="请输入姓名" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" type="email" />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入手机号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEditSubmit" :loading="editLoading">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="500px"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="当前密码" prop="currentPassword">
          <el-input
            v-model="passwordForm.currentPassword"
            type="password"
            placeholder="请输入当前密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请确认新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlePasswordSubmit" :loading="passwordLoading">
            修改
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { Edit, Lock, Plus } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { userApi } from '@/api'
import type { User } from '@/types'
import { formatDate } from '@/utils/format'

const userStore = useUserStore()

// 响应式数据
const activeTab = ref('roles')
const userInfo = ref<User>({
  id: 0,
  username: '',
  email: '',
  realName: '',
  avatar: '',
  phone: '',
  status: 'ACTIVE',
  lastLoginAt: '',
  createdAt: '',
  updatedAt: '',
  userRoles: []
} as User)
const permissionTree = ref([])
const loading = ref(true)

// 头像缓存时间戳
const avatarTimestamp = ref(Date.now())

// 计算头像URL，添加时间戳防止缓存
const avatarUrl = computed(() => {
  if (!userInfo.value.avatar) return ''
  const url = userInfo.value.avatar
  const separator = url.includes('?') ? '&' : '?'
  return `${url}${separator}t=${avatarTimestamp.value}`
})

// 编辑资料相关
const editDialogVisible = ref(false)
const editLoading = ref(false)
const editFormRef = ref<FormInstance>()
const editForm = reactive({
  realName: '',
  email: '',
  phone: '',
  avatar: ''
})

// 修改密码相关
const passwordDialogVisible = ref(false)
const passwordLoading = ref(false)
const passwordFormRef = ref<FormInstance>()
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const editRules: FormRules = {
  realName: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ]
}

const passwordRules: FormRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于 6 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    loading.value = true
    await userStore.getUserInfo()
    console.log("userStore.user",userStore.user)
    if (userStore.user) {
      userInfo.value = userStore.user
      
      // 构建权限树
      const permissions = userStore.permissions || []
      const moduleMap = new Map()
      
      permissions.forEach(permission => {
        if (!moduleMap.has(permission.module)) {
          moduleMap.set(permission.module, {
            name: permission.module,
            children: []
          })
        }
        moduleMap.get(permission.module).children.push({
          id: permission.id,
          name: permission.name,
          module: permission.module,
          action: permission.action
        })
      })
      
      permissionTree.value = Array.from(moduleMap.values())
    } else {
      ElMessage.error('获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  } finally {
    loading.value = false
  }
}

// 编辑资料
const handleEditProfile = () => {
  Object.assign(editForm, {
    realName: userInfo.value.realName || '',
    email: userInfo.value.email || '',
    phone: userInfo.value.phone || '',
    avatar: userInfo.value.avatar || ''
  })
  editDialogVisible.value = true
}

// 头像上传前验证
const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

// 头像上传处理
const handleAvatarUpload = async (options: any) => {
  try {
    const file = options.file
    
    // 上传到服务器
    const response = await userApi.uploadAvatar(file)
    
    // 更新用户信息
    if (response.data) {
      userInfo.value.avatar = response.data.avatar
      userStore.user = { ...userStore.user, avatar: response.data.avatar }
      editForm.avatar = response.data.avatar
      // 更新时间戳以刷新头像显示
      avatarTimestamp.value = Date.now()
      ElMessage.success('头像上传成功')
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败')
  }
}

// 提交编辑
const handleEditSubmit = async () => {
  if (!editFormRef.value) return
  
  try {
    await editFormRef.value.validate()
    editLoading.value = true
    
    // 调用更新用户信息的API
    const response = await userApi.updateProfile({
      realName: editForm.realName,
      email: editForm.email,
      phone: editForm.phone
    })
    
    // 更新用户信息
    if (response.data) {
      userInfo.value = { ...userInfo.value, ...response.data }
      userStore.user = { ...userStore.user, ...response.data }
    }
    
    ElMessage.success('资料更新成功')
    editDialogVisible.value = false
  } catch (error) {
    console.error('更新失败:', error)
    ElMessage.error('资料更新失败')
  } finally {
    editLoading.value = false
  }
}

// 修改密码
const handleChangePassword = () => {
  Object.assign(passwordForm, {
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
  })
  passwordDialogVisible.value = true
}

// 提交密码修改
const handlePasswordSubmit = async () => {
  if (!passwordFormRef.value) return
  
  try {
    await passwordFormRef.value.validate()
    passwordLoading.value = true
    
    // 调用修改密码的API
    await userApi.changePassword({
      currentPassword: passwordForm.currentPassword,
      newPassword: passwordForm.newPassword
    })
    
    ElMessage.success('密码修改成功')
    passwordDialogVisible.value = false
    
    // 清空表单
    Object.assign(passwordForm, {
      currentPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
  } catch (error) {
    console.error('修改失败:', error)
    ElMessage.error('密码修改失败')
  } finally {
    passwordLoading.value = false
  }
}

// 状态相关
const getStatusType = (status: string): 'success' | 'warning' | 'danger' | 'info' => {
  const statusMap: Record<string, 'success' | 'warning' | 'danger' | 'info'> = {
    ACTIVE: 'success',
    INACTIVE: 'warning',
    BANNED: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    ACTIVE: '激活',
    INACTIVE: '禁用',
    BANNED: '封禁'
  }
  return statusMap[status] || status
}

const getRoleStatusType = (status: string): 'success' | 'warning' | 'danger' | 'info' => {
  const statusMap: Record<string, 'success' | 'warning' | 'danger' | 'info'> = {
    ACTIVE: 'success',
    INACTIVE: 'warning'
  }
  return statusMap[status] || 'info'
}

const getRoleStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    ACTIVE: '激活',
    INACTIVE: '禁用'
  }
  return statusMap[status] || status
}

// 初始化
onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.profile {
  padding: 20px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
}

.profile-card {
  height: fit-content;
}

.profile-header {
  text-align: center;
  margin-bottom: 20px;
}

.profile-header h3 {
  margin: 10px 0 5px 0;
  color: #303133;
}

.profile-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.profile-info {
  margin-bottom: 20px;
}

.profile-actions {
  display: flex;
  gap: 10px;
  justify-content: center;
}

.roles-section {
  padding: 10px 0;
}

.role-card {
  margin-bottom: 15px;
}

.role-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.permissions-section {
  padding: 10px 0;
}

.permission-node {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.permission-name {
  font-weight: 500;
}

.permission-module {
  font-size: 12px;
  color: #909399;
  background-color: #f5f7fa;
  padding: 2px 6px;
  border-radius: 3px;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 